package com.tjh.springbootapi.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.tjh.springbootapi.entity.EasyPoiExport;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/easyPoiExport")
public class EasyPoiExportController {

    /**
     * 导出excel
     *
     * @param person
     * @param response
     */
    @PostMapping("/excelExport")
    public void excelExport(@RequestBody Map<String, String> person, HttpServletResponse response) throws Exception {
        List<EasyPoiExport> result = new ArrayList<>();
        EasyPoiExport easyPoiExport = new EasyPoiExport();
        easyPoiExport.setName(person.get("name"));
        easyPoiExport.setAge(22);
        result.add(easyPoiExport);
        result.add(easyPoiExport);
        String title = "导出excel";
        try {
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(title, "UTF-8"));
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("导出", "sheet"), EasyPoiExport.class, result);
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
